<template>
  <div class="table-container">
    <div class="table-header">
      <div class="button-group">
        <el-button type="primary" @click="handleAdd">新增排班信息</el-button>
      </div>
    </div>

    <div class="table-content">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        empty-text="暂无数据"
        :header-cell-style="{background: '#f5f7fa', fontWeight: 600}">

        <el-table-column
          type="index"
          label="序号"
          width="80"
          align="center">
        </el-table-column>

        <el-table-column
          prop="typesettingStartTime"
          label="排班开始时间"
          align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.typesettingStartTime) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="typesettingEndTime"
          label="排班结束时间"
          align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.typesettingEndTime) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="createUser"
          label="创建人"
          align="center">
        </el-table-column>

        <el-table-column
          label="操作"
          width="180"
          align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleDetail(scope.row)"
              :title="'详情'">
              详情
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)"
              confirm-type="warning"
              :title="'删除'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
      </el-pagination>
    </div>

    <!-- 新增排班信息弹窗 -->
    <el-dialog
      title="新增排班信息"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose">
      <el-form :model="formData" :rules="rules" ref="form">
        <el-form-item label="排班开始日期" prop="typesettingStartTime">
          <el-date-picker
            v-model="formData.typesettingStartTime"
            type="date"
            placeholder="选择开始日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="排班结束日期" prop="typesettingEndTime">
          <el-date-picker
            v-model="formData.typesettingEndTime"
            type="date"
            placeholder="选择结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 排班详情弹窗 -->
    <el-dialog
      title="排班详情"
      :visible.sync="detailDialogVisible"
      width="90%"
      :before-close="handleDetailClose">

      <div style="margin-bottom: 15px; padding: 10px; background: #f0f9eb; border-radius: 4px;">
        <strong>排班计划：</strong>
        {{ detailData.typesettingStartTime }} 至 {{ detailData.typesettingEndTime }}
        <span style="margin-left: 20px;">创建人：{{ detailData.createUser }}</span>
      </div>

      <el-table
        v-if="scheduleTableData.length > 0"
        :data="scheduleTableData"
        stripe
        border
        style="width: 100%">

        <el-table-column
          label="专业 - 岗位"
          prop="majorPosition"
          fixed
          width="220"
          align="center">
        </el-table-column>

        <el-table-column
          v-for="date in scheduleDates"
          :key="date"
          :label="formatDateShort(date)"
          :prop="date"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center;">
              <el-checkbox
                v-model="selectedCells[`${scope.$index}_${date}`]"
                :disabled="loadingStaff"
                style="margin-right: 10px;">
              </el-checkbox>
              <el-select
                v-model="scope.row[date]"
                placeholder="请选择人员"
                style="flex: 1"
                @change="updateScheduleCell(scope.row, date)"
                :disabled="loadingStaff">
                <el-option
                  v-for="staff in staffList"
                  :key="staff.id"
                  :label="staff.name"
                  :value="staff.name">
                </el-option>
                <el-option
                  label="未安排"
                  value="未安排">
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div v-else style="text-align: center; padding: 40px; color: #999;">
        暂无排班数据
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="clearAllSelection">清空选中</el-button>
        <el-button type="primary" @click="batchFillSelected" :disabled="!getSelectedCellsCount()">批量填充</el-button>
        <el-button @click="handleDetailClose">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 批量填充弹窗 -->
    <el-dialog
      title="批量填充人员"
      :visible.sync="batchFillDialogVisible"
      width="400px"
      :before-close="handleBatchFillClose">

      <div style="margin-bottom: 20px;">
        <p>已选择 {{ getSelectedCellsCount() }} 个单元格</p>
      </div>

      <el-form :model="{ staffName: batchFillStaffName }" ref="batchFillForm">
        <el-form-item label="选择人员" prop="staffName" :label-width="80">
          <el-select
            v-model="batchFillStaffName"
            placeholder="请选择要填充的人员"
            style="width: 100%"
            :disabled="loadingStaff">
            <el-option
              v-for="staff in staffList"
              :key="staff.id"
              :label="staff.name"
              :value="staff.name">
            </el-option>
            <el-option
              label="未安排"
              value="未安排">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleBatchFillClose">取消</el-button>
        <el-button type="primary" @click="confirmBatchFill">确定填充</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TypesettingTable',
  data: function () {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      dialogVisible: false,
      loading: false,
      detailDialogVisible: false,
      detailData: {},
      scheduleTableData: [],
      scheduleDates: [],
      staffList: [], // 人员列表
      loadingStaff: false, // 加载人员列表的状态
      selectedCells: {}, // 存储选中的单元格状态，格式：{rowIndex_date: boolean},
      cellIdMap: {}, // 存储单元格ID映射关系
      batchFillDialogVisible: false, // 批量填充弹窗可见性
      batchFillStaffName: '', // 批量填充选择的人员名称,
      formData: {
        typesettingStartTime: '',
        typesettingEndTime: ''
      },
      rules: {
        typesettingStartTime: [
          { required: true, message: '请选择排班开始日期', trigger: 'blur' }
        ],
        typesettingEndTime: [
          { required: true, message: '请选择排班结束日期', trigger: 'blur' },
          {
            validator:  (rule, value, callback) =>{
              if (this.formData.typesettingStartTime && value) {
                if (new Date(value) <= new Date(this.formData.typesettingStartTime)) {
                  callback(new Error('排班结束日期必须大于开始日期'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted: function () {
    this.loadTableData()
  },
  methods: {
    loadTableData: function () {
      this.loading = true

      var proxy = {
        url: 'pbglschedulemaster/list',
        datas: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          type: 1
        }
      }

      this.$oPost({ proxy }, (response) => {
        this.loading = false
        if (response && response.code === 1000 && response.data) {
          if (Array.isArray(response.data.list)) {
            this.tableData = []
            for (var i = 0; i < response.data.list.length; i++) {
              var item = response.data.list[i]
              this.tableData.push({
                id: item.id,
                typesettingStartTime: item.startDate || item.typesettingStartTime,
                typesettingEndTime: item.endDate || item.typesettingEndTime,
                createTime: item.createdTime || item.createTime,
                createUser: item.createdBy || item.createUser
              })
            }
            this.totalCount = response.data.total || this.tableData.length
          } else {
            this.$message.error('获取数据失败')
          }
        } else {
          this.$message.error('获取数据失败')
        }
      }, (error) => {
        this.loading = false
        this.$message.error('获取数据时发生错误')
      })
    },

    formatDate: function (dateString) {
      if (!dateString) return ''
      return dateString
    },

    formatDateShort: function (dateString) {
      if (!dateString) return ''
      var date = new Date(dateString)
      var month = date.getMonth() + 1
      var day = date.getDate()
      return month + '月' + day + '日'
    },

    handleDelete: function (id) {
      this.$confirm('确定要删除这条数据吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        var proxy = {
          url: 'pbglschedulemaster/delete?id=' + id,
          datas: {}
        }

        this.$oPost({ proxy }, (response) => {
          this.loading = false
          if (response && response.code === 1000) {
            var newTableData = []
            for (var i = 0; i < this.tableData.length; i++) {
              if (this.tableData[i].id !== id) {
                newTableData.push(this.tableData[i])
              }
            }
            this.tableData = newTableData
            this.totalCount = this.tableData.length
            this.$message.success('删除成功')
          } else {
            this.$message.error(response ? response.msg || '删除失败' : '删除失败')
          }
        }, (error) => {
          this.loading = false
          this.$message.error('删除时发生错误')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    handleSizeChange: function (size) {
      this.pageSize = size
      this.loadTableData()
    },

    handleCurrentChange: function (current) {
      this.currentPage = current
      this.loadTableData()
    },

    handleAdd: function () {
      this.formData = {
        typesettingStartTime: '',
        typesettingEndTime: ''
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.dialogVisible = true
    },

    // ✅ 改为箭头函数，无 _this，专业排序已加入
    handleDetail: function (rowData) {
      this.loading = true // ✅ this 正常指向 Vue 实例

      var proxy = {
        url: '/pbglschedulecell/detail?id=' + rowData.id,
        datas: {}
      }

      this.$oPost({ proxy }, (response) => {
        this.loading = false

        if (response && response.code === 1000) {
          if (response.data && response.data.list && Array.isArray(response.data.list)) {
            this.detailData = {}
            for (var key in rowData) {
              this.detailData[key] = rowData[key]
            }

            var transformResult = this.transformToScheduleTable(response.data.list)
            this.scheduleTableData = transformResult.rows
            this.scheduleDates = transformResult.dates

            // 获取人员列表用于下拉选择
            this.getStaffList()

            this.detailDialogVisible = true
          } else {
            this.$message.error('返回数据格式错误或无排班数据')
          }
        } else {
          this.$message.error('获取排班详情失败：' + (response.msg || '未知错误'))
        }
      }, (error) => {
        this.loading = false
        this.$message.error('网络请求失败')
      })
    },

    // 获取人员列表
    getStaffList: function () {
      this.loadingStaff = true

      var proxy = {
        url: '/pbglstaff/list', // 假设的人员列表API接口
        datas: {}
      }

      this.$oPost({ proxy }, (response) => {
        this.loadingStaff = false

        if (response && response.code === 1000 && response.data && Array.isArray(response.data)) {
          this.staffList = response.data
        } else {
          // 如果API调用失败，使用一个默认的人员列表
          this.staffList = [
            { id: '1', name: '张三' },
            { id: '2', name: '李四' },
            { id: '3', name: '王五' },
            { id: '4', name: '赵六' }
          ]
          console.log('使用默认人员列表')
        }
      }, (error) => {
        this.loadingStaff = false
        // 网络请求失败时使用默认人员列表
        this.staffList = [
          { id: '1', name: '张三' },
          { id: '2', name: '李四' },
          { id: '3', name: '王五' },
          { id: '4', name: '赵六' }
        ]
        console.log('网络请求失败，使用默认人员列表')
      })
    },

    // 更新排班单元格人员信息
    updateScheduleCell: function (row, date) {
      // 解析专业和岗位
      var majorPosition = row.majorPosition
      var parts = majorPosition.split(' - ')
      var major = parts[0]
      var position = parts[1]

      var staffName = row[date]

      // 构建单元格的唯一键，用于从映射表中获取ID
      var cellKey = majorPosition + '_' + date
      var cellId = this.cellIdMap && this.cellIdMap[cellKey] ? this.cellIdMap[cellKey] : null

      // 从staffList中查找与员工名称匹配的员工ID
      var staffId = null
      if (staffName && staffName !== '未安排' && this.staffList && this.staffList.length > 0) {
        var staff = this.staffList.find(function(item) {
          return item.name === staffName
        })
        if (staff && staff.id) {
          staffId = staff.id
        }
      }

      var proxy = {
        url: 'pbglschedulecell/update', // 假设的更新API接口
        datas: {
          id: cellId, // 包含单元格的原始ID
          scheduleId: this.detailData.id,
          cellDate: date,
          major: major,
          position: position,
          staffName: staffName === '未安排' ? '' : staffName,
          staffId: staffId // 包含员工ID
        }
      }

      this.$oPost({ proxy }, (response) => {
        if (response && response.code === 1000) {
          this.$message.success('排班更新成功')
        } else {
          this.$message.error('排班更新失败：' + (response.msg || '未知错误'))
        }
      }, (error) => {
        this.$message.error('网络请求失败')
        // 如果更新失败，恢复原来的值
        row[date] = ''
      })
    },

    // ✅ 加入专业排序：方式、水新、调度、现货、自动化
    transformToScheduleTable: function (cellList) {
      // 1. 提取所有唯一日期
      var dateMap = {}
      for (var i = 0; i < cellList.length; i++) {
        var cell = cellList[i]
        dateMap[cell.cellDate] = true
      }
      var dates = []
      for (var date in dateMap) {
        dates.push(date)
      }
      // 手动排序日期
      dates.sort(function (a, b) {
        return new Date(a) - new Date(b)
      })

      // 2. 按“专业 - 岗位”分组
      var groupMap = {}
      // 用于存储每个单元格的原始ID信息
      var cellIdMap = {}
      for (var i = 0; i < cellList.length; i++) {
        var cell = cellList[i]
        var key = cell.major + ' - ' + cell.position
        var cellKey = key + '_' + cell.cellDate
        if (!groupMap[key]) {
          groupMap[key] = {
            majorPosition: key,
            _major: cell.major // 临时保存专业用于排序
          }
          for (var j = 0; j < dates.length; j++) {
            groupMap[key][dates[j]] = ''
          }
        }
        groupMap[key][cell.cellDate] = cell.staffName || '未安排'
        // 保存单元格ID信息
        cellIdMap[cellKey] = cell.id
      }
      // 保存单元格ID映射到Vue实例，供后续更新使用
      this.cellIdMap = cellIdMap

      // 3. 转成数组
      var rows = []
      for (var key in groupMap) {
        rows.push(groupMap[key])
      }

      // ✅ 按指定专业顺序排序
      var majorOrder = ['方式', '水新', '调度', '现货', '自动化']
      rows.sort(function (a, b) {
        var indexA = majorOrder.indexOf(a._major)
        var indexB = majorOrder.indexOf(b._major)
        // 如果专业不在列表中，放在最后
        if (indexA === -1) indexA = 999
        if (indexB === -1) indexB = 999
        return indexA - indexB
      })

      // 4. 删除临时字段 _major
      for (var i = 0; i < rows.length; i++) {
        delete rows[i]._major
      }

      return {
        rows: rows,
        dates: dates
      }
    },

    handleClose: function () {
      this.dialogVisible = false
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },

    handleDetailClose: function () {
      this.detailDialogVisible = false
      this.detailData = {}
      this.scheduleTableData = []
      this.scheduleDates = []
      this.selectedCells = {} // 清空选中状态
    },

    handleSubmit: function () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var proxy = {
            url: 'pbglschedulemaster/add',
            datas: {
              startDate: this.formData.typesettingStartTime,
              endDate: this.formData.typesettingEndTime,
              type: '1'
            }
          }

          this.$oPost({ proxy }, (response) => {
            if (response && response.code === 1000) {
              this.$message.success('新增排班信息成功')
              this.dialogVisible = false
              this.loadTableData()
            } else {
              this.$message.error('新增失败：' + (response.msg || '未知错误'))
            }
          }, (error) => {
            this.$message.error('新增排班信息时发生错误')
          })
        }
      })
    },

    // 获取选中的单元格数量
    getSelectedCellsCount: function () {
      var count = 0
      for (var key in this.selectedCells) {
        if (this.selectedCells[key]) {
          count++
        }
      }
      return count
    },

    // 清空所有选中状态
    clearAllSelection: function () {
      // 1. 创建一个新的空对象并使用Vue.set确保响应式
      const emptyObj = {}
      if (this.$set) {
        this.$set(this, 'selectedCells', emptyObj)
      } else {
        this.selectedCells = emptyObj
      }

      // 2. 强制触发视图更新
      this.$forceUpdate()

      // 3. 使用Vue.nextTick确保DOM更新后，手动清除checkbox的选中状态
      this.$nextTick(() => {
        // 查找详情弹窗中的所有复选框
        const checkboxes = document.querySelectorAll('.el-dialog__wrapper .el-checkbox__input.is-checked')
        checkboxes.forEach(checkbox => {
          // 直接操作DOM清除选中状态
          checkbox.classList.remove('is-checked')
          // 找到input元素并取消选中
          const input = checkbox.querySelector('input[type="checkbox"]')
          if (input) {
            input.checked = false
          }
        })
      })
    },

    // 批量填充选中的单元格
    batchFillSelected: function () {
      this.batchFillDialogVisible = true
      this.batchFillStaffName = ''
    },

    // 关闭批量填充弹窗
    handleBatchFillClose: function () {
      this.batchFillDialogVisible = false
      this.batchFillStaffName = ''
    },

    // 确认批量填充
    confirmBatchFill: function () {
      if (!this.batchFillStaffName) {
        this.$message.warning('请选择要填充的人员')
        return
      }

      this.loadingStaff = true
      var batchUpdateData = []

      // 遍历选中的单元格
      for (var key in this.selectedCells) {
        if (this.selectedCells[key]) {
          var keyParts = key.split('_')
          var rowIndex = keyParts[0]
          var date = keyParts[1]
          var row = this.scheduleTableData[rowIndex]

          // 解析专业和岗位
          var majorPosition = row.majorPosition
          var parts = majorPosition.split(' - ')
          var major = parts[0]
          var position = parts[1]

          // 更新本地数据
          row[date] = this.batchFillStaffName

          // 从staffList中查找与员工名称匹配的员工ID
          var staffId = null
          if (this.batchFillStaffName && this.batchFillStaffName !== '未安排' && this.staffList && this.staffList.length > 0) {
            var staff = this.staffList.find(function(item) {
              return item.name === this.batchFillStaffName
            }.bind(this))
            if (staff && staff.id) {
              staffId = staff.id
            }
          }

          // 构建单元格的唯一键，用于从映射表中获取ID
          var cellKey = majorPosition + '_' + date
          var cellId = this.cellIdMap && this.cellIdMap[cellKey] ? this.cellIdMap[cellKey] : null

          // 添加到批量更新数组
          batchUpdateData.push({
            id: cellId, // 包含单元格的原始ID
            scheduleId: this.detailData.id,
            cellDate: date,
            major: major,
            position: position,
            staffName: this.batchFillStaffName === '未安排' ? '' : this.batchFillStaffName,
            staffId: staffId
          })
        }
      }

      // 调用批量更新API
      var proxy = {
        url: 'pbglschedulecell/batchUpdate', // 假设的批量更新API接口
        datas: batchUpdateData
      }

      this.$oPost({ proxy }, (response) => {
        this.loadingStaff = false
        this.batchFillDialogVisible = false

        if (response && response.code === 1000) {
          this.$message.success('成功批量更新' + batchUpdateData.length + '个单元格')
          this.clearAllSelection()
        } else {
          this.$message.error('批量更新失败：' + (response.msg || '未知错误'))
        }
      }, (error) => {
        this.loadingStaff = false
        this.batchFillDialogVisible = false
        this.$message.error('网络请求失败')
      })
    }
  }
}
</script>

<style scoped>
.table-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.table-header {
  margin-bottom: 20px;
}

.table-content {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}

.button-group {
  margin-bottom: 15px;
}
</style>
